package itsm.isperp.module.controller.app;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.service.BaseService;
import itsm.isperp.framework.utils.FileUtils;
import itsm.isperp.framework.utils.Pair;
import itsm.isperp.framework.web.controller.BaseController;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.app.AppConfig;
import itsm.isperp.module.entity.customer.CusCustomer;
import itsm.isperp.module.service.app.AppConfigService;
import itsm.isperp.module.service.app.AppDepartmentService;
import itsm.isperp.module.service.app.AppUserService;
import itsm.isperp.module.service.customer.CusCustomerService;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/app/appConfig")
public class AppConfigController extends BaseController<AppConfig> {

	/**
	 * 
	 */
	@Autowired
	protected AppConfigService appConfigService;

	@Override
	public BaseService<AppConfig> getService() {
		return appConfigService;
	}

	@Override
	public String getPageTitle() {
		return "常规配置";
	}

	/**
	 * 管理界面
	 * 
	 * @return 常规配置视图
	 */
	@RequestMapping(value = { "manage", "" })
	public ModelAndView manage(HttpServletRequest req) {
		ModelAndView mv = this.getModelAndView();
		List<AppConfig> list = appConfigService.findAll();
		for (AppConfig appConfig : list) {
			mv.addObject(appConfig.getItemKey(), appConfig.getItemValue());
		}

		return mv;

	}

	@RequestMapping(value = { "readMailEdit", "readMail" })
	public ModelAndView readMailEdit(HttpServletRequest req) {
		ModelAndView mv = this.getModelAndView();
		List<AppConfig> list = appConfigService.findAll();
		for (AppConfig appConfig : list) {
			mv.addObject(appConfig.getItemKey(), appConfig.getItemValue());
		}

		return mv;

	}

	@RequestMapping(value = { "adManage" })
	public ModelAndView adManage(HttpServletRequest req) {
		ModelAndView mv = this.getModelAndView();
		List<AppConfig> list = appConfigService.findAll();
		for (AppConfig appConfig : list) {
			mv.addObject(appConfig.getItemKey(), appConfig.getItemValue());
		}

		CusCustomerService cusCustomerService = ContextHolder
				.getSpringBean("cusCustomerService");
		CusCustomer c = cusCustomerService.findOne(ContextHolder
				.getConfigByKey("adCustomer"));
		mv.addObject("cusCustomerName", c == null ? "" : c.getName());

		return mv;

	}

	/**
	 * 保存配置项
	 * 
	 * @param model
	 *            　
	 * @return json结果数据
	 * @throws IOException
	 */
	@RequestMapping("save")
	@ResponseBody
	public ResultMessage save(AppConfig model, HttpServletRequest req) {

		Enumeration<String> enumeration = req.getParameterNames();

		List<Pair<String, String>> ps = new ArrayList<Pair<String, String>>();
		// List<AppConfig> list=null;
		while (enumeration.hasMoreElements()) {
			String pName = enumeration.nextElement().toString();
			String pValue = req.getParameterValues(pName)[0];

			if ("apkFilePath".equals(pName)) {
				String apkPath = ContextHolder.getUploadFileStore()
						+ "global/itsm_app_apk"
						+ FileUtils.getFileExtname(pValue);

				if (!apkPath.equals(pValue)) {

					String apkFile = ContextHolder.getApplicationPath()
							+ pValue;

					File sourceFile = new File(apkFile);
					File targetFile = new File(
							ContextHolder.getApplicationPath() + apkPath);

					try {
						FileUtils.copyFile(sourceFile, targetFile);
						sourceFile.delete();

						pValue = apkPath;
					} catch (IOException e) {

					}

				}

			}

			ps.add(new Pair<>(pName, pValue));

		}

		appConfigService.saveOrUpdate(ps);
		return ResultMessage.newInstance(true);
	}

	@RequestMapping("syncFromLdap")
	@ResponseBody
	public ResultMessage syncFromLdap() {

		AppDepartmentService appDepartmentService = ContextHolder
				.getSpringBean("appDepartmentService");

		AppUserService appUserService = ContextHolder
				.getSpringBean("appUserService");

		try {
			appDepartmentService.syncUnitData();
		} catch (NamingException e) {
			return ResultMessage.success("同步组织失败，原因是：" + e.getMessage());
		}
		try {
			appUserService.syncUserData();
		} catch (NamingException e) {
			return ResultMessage.success("同步组织用户失败，原因是：" + e.getMessage());
		}

		return ResultMessage.success();
	}
	
	

}
